import React from 'react';
import {connect} from 'dva'
import moment from 'moment'


import { DatePicker, List } from 'antd-mobile';
import { CommAbstract } from 'components/Abstract'
import Title from 'components/Title'
import Chart from 'components/Chart'
import AnalysisTitle from 'components/AnalysisTitle';
import TopNavBar from 'components/TopNavBar';
import Indicators from './components/Indicators'
import Statistics from './components/Statistics'

import Tools from 'utils/tools';

import { config } from 'utils'
const { scada } = config;
const {
  Token,DType,StationIds
} = scada;
const {
  source,supply,drug
} = StationIds;

const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const time = moment(now).format('YYYY')

@connect(({production}) => ({...production}))
class Production extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      time,
      monthList: [],
      lastYearMonthList:[]
    }

    this.Conf = {
      echartsConf: [
        {
          key: 'slfx3',
          label: '源水利用率',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [
                { name: '利用率', field: 'sourceSupplyPrec', type: 'line', yAxisIndex: 1 },
                { name: '未利用源水', field: 'unUsedSource', type: 'bar',  barWidth:'25%'},
                { name: '已利用源水', field: 'supply', type: 'bar', barWidth:'25%' }
              ],
              yAxis: [{ name: '万m³' }, { name: '%'}],
            },
            color: ['251, 212, 55','78, 203, 115', '68, 130, 255',  '134, 147, 243'],
            other: { showLegend: true },
          }
        },
        {
          key: 'slfx4',
          label: '供水用电情况',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [
                { name: '用电量', field: 'electric', type: 'line', areaStyle: {}}
              ],
              yAxis: [{ name: '万kw.h' }],
            },
            color: [ '68, 130, 255', '251, 212, 55','78, 203, 115', '134, 147, 243'],
            other: { showLegend: true },
          }
        },
        {
          key: 'fd',
          label: '费用分析',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [{name: '电费', field: 'electric_cost',type: 'bar',  barWidth:'25%'}],
              yAxis: [{ name: '万元' }],
            },
            color: [ '68, 130, 255', '251, 212, 55','78, 203, 115', '134, 147, 243'],
            other: { showLegend: true },
          }
        },
        {
          key: 'slfx5',
          label: '物质消耗情况',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [
                { name: '盐酸', field: 'drugHCL', type: 'line'},
                { name: '氯酸钠', field: 'drugNaClO3', type: 'line'}
              ],
              yAxis: [{ name: 'kg' }],
            },
            color: [ '68, 130, 255', '78, 203, 115','251, 212, 55', '134, 147, 243'],
            other: { showLegend: true },
          }
        },
        {
          key: 'fd2',
          label: '费用分析',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [{name: '药剂费用', field: 'drug_cost',type: 'bar',  barWidth:'25%'}],
              yAxis: [{ name: '万元' }]
            },
            color: [ '68, 130, 255', '251, 212, 55','78, 203, 115', '134, 147, 243'],
            other: { showLegend: true }
          }
        },
        {
          key: 'fd3',
          label: '成本分析',
          chart: {
            type: 'Common2',
            columns: {
              seriesItems: [{name: '一吨水成本价', field: 'supply_cost',type: 'bar',  barWidth:'25%'}],
              yAxis: [{ name: '元' }],
            },
            color: [ '68, 130, 255', '251, 212, 55','78, 203, 115', '134, 147, 243'],
            other: { showLegend: true },
          }
        }
      ]
    }
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    await this.setDateECharts()
  }

  // 获取指标
  setDateECharts = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    const lastYearMonthList = Tools.getFullMonth(time-1);
    this.setState({
      monthList:monthList,lastYearMonthList:lastYearMonthList
    })
    /*源水量
    */
    source.map((item, idx) => {
      let server = {type: 'production/querySource',payload: { Token: Token,DTypes:["SJLJ"], Interval: 86400, Begin: moment(`${time}-01-01 00:00:00`).unix(),
          End: moment(`${time}-12-31 23:59:59`).unix(),StationId: item,type: "2"+ idx} };
      this.querySJLJIndicators(server);
    })

    /*上一年源水量
   */
    source.map((item, idx) => {
      let server = {type: 'production/querySource',payload: { Token: Token,DTypes:["SJLJ"], Interval: 86400, Begin: moment(`${time-1}-01-01 00:00:00`).unix(),
          End: moment(`${time-1}-12-31 23:59:59`).unix(),StationId: item,type: "3"+ idx} };
      this.querySJLJIndicators(server);
    })

    /*供水量
     */
    let serverS = {type: 'production/querySupply',payload: { Token: Token,DTypes:["SJLJ"], Interval: 86400,
        Begin: moment(`${time}-01-01 00:00:00`).unix(),End: moment(`${time}-12-31 23:59:59`).unix(),StationId: supply[0],type: 2 } };
    this.querySJLJIndicators(serverS);

    /*上一年供水量
    */
    let serverSN = {type: 'production/querySupply',payload: { Token: Token,DTypes:["SJLJ"], Interval: 86400,
        Begin: moment(`${time-1}-01-01 00:00:00`).unix(),End: moment(`${time-1}-12-31 23:59:59`).unix(),StationId: supply[0],type: 3 } };
    this.querySJLJIndicators(serverS);

    /*药耗
     */
    let serverD = {type: 'production/queryDrug',payload:{payload: { where: `DATATIME>='${time}0101' and DATATIME<='${time}1231'` },tablename: 'zddrugmanage',type: 2}}
    this.querySJLJIndicators(serverD);

    /*电耗
     */
    let serverE = {type: 'production/queryElectric',payload:{payload: { where: `DATATIME>='${time}0101' and DATATIME<='${time}1231'` },tablename: 'zdelectricmanage',type: 2}}
    this.querySJLJIndicators(serverE);


  }

  querySJLJIndicators = async (server) => {
    await this.props.dispatch(server);
  }


  // 标题
  RenderNavBar = () => {
    const { route } = this.props;
    return <TopNavBar title={route.title} />;
  }

  // 图表渲染
  RenderECharts = () => {
    const { echartsConf } = this.Conf;
    const { props, state } = this;
    const { monthList,lastYearMonthList } = state;

    let resource = {
      source: [], sourceT: [], sourceR: [],  //源水，源水同比，源水环比
      supply: [], supplyT: [], supplyR: [], sourceSupplyPrec: [], unUsedSource: [], //供水水，供水同比，供水环比，源水利用率
      drugNaClO3: [], drugHCL: [], electric: [], //氯酸钠，盐酸 ,用电量
      electric_cost:[],drug_cost:[],supply_cost:[]} //电费，药费，一吨水成本
    let time = []

    //封装上一年的源水和供水数据
    let lastYearMonthSourceVals = {};
    let lastYearMonthSupplyVals = {};
    let lastMonthSourceVal = 0;
    let lastMonthSupplyVal = 0;
    lastYearMonthList.map(ele => {
      // 每月第一天 和 最后一天
      const startTimestamp = moment(moment(ele).startOf('month')).unix();
      const endTimestamp = moment(moment(ele).endOf('month')).unix();

      const months = moment(ele).month();
      let sourceSum = 0,supplySum = 0;
      source.map((item, idx) => {
        const resouseVals = this.props[`SourceResourc3${idx}`] && this.props[`SourceResource3${idx}`][0] && this.props[`SourceResource3${idx}`][0].Vals
          ? this.props[`SourceResource3${idx}`][0].Vals : [];
        resouseVals.map(term => {
          const {Time, Report} = term;
          const {maxv} = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            sourceSum += maxv
          }
        })
      })
      lastYearMonthSourceVals[months] = sourceSum;
      lastMonthSourceVal = sourceSum;
      const supplyVals = this.props["SupplyResource3"] && this.props["SupplyResource3"][0] && this.props["SupplyResource3"][0].Vals
        ? this.props["SupplyResource3"][0].Vals : [];
      supplyVals.map(term => {
          const { Time,Report } = term;
          const { maxv } = Report;
        if(Time >= startTimestamp && Time <= endTimestamp ){
          supplySum += maxv
        }
        }
      )
      lastYearMonthSupplyVals[months] = supplySum;
      lastMonthSupplyVal = supplySum;
    })

    monthList.map(ele => {
      // 每月第一天 和 最后一天
      const startTimestamp = moment(moment(ele).startOf('month')).unix();
      const endTimestamp = moment(moment(ele).endOf('month')).unix();
      const months = moment(ele).month();
      // 处理时间
      time.push(moment(ele).format('M月'))
      //获取源水量
      let sourceSum = 0;
      source.map((item, idx) => {
        const resouseVals = this.props[`SourceResource2${idx}`] && this.props[`SourceResource2${idx}`][0] && this.props[`SourceResource2${idx}`][0].Vals
          ? this.props[`SourceResource2${idx}`][0].Vals : [];
        resouseVals.map(term => {
          const {Time, Report} = term;
          const {maxv} = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            sourceSum += maxv
          }
        })
      })
      resource.source.push((sourceSum/10000).toFixed(2));
      resource.sourceT.push(lastYearMonthSourceVals[months] ? ((sourceSum-lastYearMonthSourceVals[months])*100.0/lastYearMonthSourceVals[months]).toFixed(1) : 0);
      resource.sourceR.push(lastMonthSourceVal ? ((sourceSum-lastMonthSourceVal)*100.0/lastMonthSourceVal).toFixed(1): 0);
      lastMonthSourceVal = sourceSum;
      //获取供水量
      let supplySum = 0;
      const supplyVals = this.props["SupplyResource2"] && this.props["SupplyResource2"][0] && this.props["SupplyResource2"][0].Vals
        ? this.props["SupplyResource2"][0].Vals : [];
      supplyVals.map(term => {
          const { Time,Report } = term;
          const { maxv } = Report;
          if(Time >= startTimestamp && Time <= endTimestamp ){
            supplySum += maxv
          }
        }
      )
      resource.supply.push((supplySum/10000).toFixed(2));
      resource.supplyT.push(lastYearMonthSupplyVals[months] ? ((supplySum-lastYearMonthSupplyVals[months])*100.0/lastYearMonthSupplyVals[months]).toFixed(1) : 0);
      resource.supplyR.push(lastMonthSupplyVal ? ((supplySum-lastMonthSupplyVal)*100.0/lastMonthSupplyVal).toFixed(1): 0);
      resource.unUsedSource.push(((sourceSum-supplySum)/10000).toFixed(2));
      resource.sourceSupplyPrec.push(sourceSum ? (supplySum*100.0/sourceSum).toFixed(1) : 0)
      lastMonthSupplyVal = supplySum;

      //获取氯酸钠，盐酸
      let naClO3Sum = 0,hClSum = 0,drugCost = 0;
      const drugVals = this.props["DrugResource2"] ? this.props["DrugResource2"] : [];
      drugVals.map(ele => {
        const { attributes } = ele;
        let { DATATIME,NAClO3,HYDROCHLORIC_ACID,NACLO3_COST,HCL_COST } = attributes;
        const Time =  moment(DATATIME, "YYYY-MM-DD").unix();
        if(Time >= startTimestamp && Time <= endTimestamp ){
          naClO3Sum += (NAClO3?parseFloat(NAClO3):0);
          hClSum += (HYDROCHLORIC_ACID?parseFloat(HYDROCHLORIC_ACID):0);
          drugCost += (NACLO3_COST?NACLO3_COST * 100:0);
          drugCost += (HCL_COST?HCL_COST * 100:0);
        }
      })
      resource.drugNaClO3.push(naClO3Sum);resource.drugHCL.push(hClSum);
      resource.drug_cost.push(drugCost/100);
      //获取用电量
      let electricSum = 0,electricCost = 0;
      const electricVals = this.props["ElectricResource2"] ? this.props["ElectricResource2"] : [];
      electricVals.map(ele => {
        const { attributes } = ele;
        let { DATATIME,ELECTRICITY_CONSUMPTION,ELECTRICITY_COST} = attributes;
        const Time =  moment(DATATIME, "YYYY-MM-DD").unix();
        if(Time >= startTimestamp && Time <= endTimestamp ){
          electricSum +=  (ELECTRICITY_CONSUMPTION?parseFloat(ELECTRICITY_CONSUMPTION):0);
          electricCost += (ELECTRICITY_COST?parseFloat(ELECTRICITY_COST):0);
        }
      })
      resource.electric.push(electricSum);
      resource.electric_cost.push(electricCost);
      resource.supply_cost.push(supplySum ? ((electricCost+drugCost)*10000/supplySum).toFixed(2):0);
    })

    let charts = null;
    charts = echartsConf.map(ele => {
      const { key, label, chart, extra } = ele;
      const { type: chartType, columns, color, other } = chart;

      const dataSource = {};
      columns['seriesItems'].forEach(ele => {
        const { field } = ele;
        Object.assign(ele, { data: resource[field]})
      })

      Object.assign(dataSource, { time, data: columns['seriesItems'] })

      return (
        <Title key={key} title={label}>
          <Chart
            type={chartType}
            color={color}
            columns={columns}
            dataSource={dataSource}
            extra = {extra}
            other = {other}
          />
        </Title>
      )
    })
    return <>{charts}</>
  }

  // 格式化时间
  formatDate(date){
    const yearStr = `${date.getFullYear()}年`;
    return yearStr;
  }
  // 时间插件
  RenderDatePicker = () => {
    const { time } = this.state;
    const value = moment(time, 'YYYY').toDate()
    return (
      <List>
        <DatePicker
          mode="year"
          title="选择时间"
          value={value}
          format={val => `${this.formatDate(val)}`}
          onChange={e => this.handleChange(e)}
        >
          <List.Item arrow="horizontal">选择时间：</List.Item>
        </DatePicker>
      </List>
    )
  }
  // change
  handleChange = (data) => {
    const lastTime = this.state.time;
    const time = moment(data).format('YYYY')
    if(lastTime === time){
      return;
    }
    this.setState({
      time
    }, async () =>{
      await this.setDateECharts()
    })
  }

  render() {
    const { time } = this.state;
    return (
      <div>
        {this.RenderNavBar()}
        <Indicators />
        <AnalysisTitle />
        {this.RenderDatePicker()}
        <Statistics
          defaultValue = {time}/>
        {this.RenderECharts()}
      </div>
    )
  }
}

export default Production;
